package com.pricecmp.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.pricecmp.dao.DAOFacade;
import com.pricecmp.model.Comment;
import com.pricecmp.model.Good;
import com.pricecmp.service.SearchService;

public class SearchServiceImpl implements SearchService {
	private DAOFacade dao;

	@Override
	public List<Good> search(String userInput) {
		// ���зִʵ�Ԥ����
		List<String> words = this.parseInput(userInput);
		// ����ͬ���ת��
		List<String> synonyms = dao.getSynonyms(words);
		// ���в�ѯ
		List<Good> result = dao.getGoodBySynonyms(synonyms);
		// ��ݾ��۹������Ʒ����
		this.sortGoods(result);
		for(int i=0;i<result.size();i++)
		{
			if(result.get(i).getPrice().equals("0"))
				result.remove(i);
		}
		return result;
	}

	/**
	 * ���û���������в��
	 * 
	 * @param userInput
	 * @return ���ز�ֺ�ĵ��ʣ����ܷ���null
	 */
	private List<String> parseInput(String userInput) {
		String[] inputArray = userInput.split("\\s+");
		List<String> temp = Arrays.asList(inputArray);
		List<String> words = new ArrayList<String>(temp);
		return words;
	}

	/**
	 * ��ݾ��۹������Ʒ��������
	 * 
	 * @param goods
	 */
	private void sortGoods(List<Good> goods) {
		Collections.sort(goods);
	}

	@Override
	public Good getGoodsInfo(long id) {
		return dao.getGoodsInfo(id);
	}

	@Override
	public List<Comment> getComments(long id) {
		return dao.getGoodsComment(id);
	}

	public DAOFacade getDao() {
		return dao;
	}

	public void setDao(DAOFacade dao) {
		this.dao = dao;
	}

}
